package com.myfum.wingplayer.utils
{
	import com.myfum.wingplayer.Config;
	import com.myfum.wingplayer.components.ui.Program;
	import com.myfum.wingplayer.entity.ProjectData;
	
	import flash.events.Event;
	
	import mx.core.UIComponent;
	
	public class ProjectManager extends UIComponent
	{
		public function ProjectManager()
		{
			super();
			init();
		}
		
		private var _projectData:ProjectData;
		private var _currentProject:Program;
		private var _container:UIComponent;
		
		private var _taskManager:TaskManager;
		
		private function init():void{
			_container = new UIComponent();
			addChild(_container);
			
			_taskManager = TaskManager.instance;
			_taskManager.addEventListener(TaskManager.PROJECT_CHANGE, onProjectChange);
			_taskManager.addEventListener(TaskManager.PROJECT_EMPTY, onProjectEmpty);
		}
		
		private function initProject():void{
			_currentProject = new Program();
			_currentProject.data = _projectData;
			_container.addChild(_currentProject);
		}
		
		private function onProjectChange(evt:Event):void{
			switchTo(_taskManager.getCurrentProject());
		}
		
		private function onProjectEmpty(evt:Event):void{
			if(_projectData == null || _projectData.id != Config.DEFAULT_PROJECT_ID){
				switchTo(null);
			}
		}
		
		public function switchTo(projectData:ProjectData):void{
			dispose();
			if(projectData){
				_projectData = projectData;
				initProject();
			}else{
				//play myfum default Ads
				_projectData = new ProjectData();
				_projectData.id = Config.DEFAULT_PROJECT_ID;
				initProject();
			}
		}
		
		private function dispose():void{
			if(_currentProject){
				_currentProject.dispose();
				/*_container.removeChild(_currentProject);
				_currentProject = null;*/
			}
		}
	}
}